<?php
namespace app\admin\controller;
use app\common\controller\Adminbase;
use \think\Loader;
use \think\Db;

// +----------------------------------------------------------------------
// | XpCms
// +----------------------------------------------------------------------
// | Copyright (c) 2021-2099
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Mercurio（Xp） <725668993@qq.com>
// +----------------------------------------------------------------------

/*
** 文章分类 控制器
*/

class Template extends Adminbase {
    private static $_options 	= null; // 数据表对象
	
	// 优先加载
	public function _initialize() {
		parent::_initialize();
		self::$_options = Db::name('Options');
		$content = self::$_options -> where(array('title' => 'siteinfo')) -> value('content');
		$site = json_decode($content, true);
		$this->template_path = './tpl/home/'.$site['template'].'/';
		$this->assign('html', $this->template_html);//自定义html目录
	}
	
	// 分类列表
	public function index() {
		$type = 'html';
		$path = $this->template_path;
		$files = dir_list($path,$type);
		$templates = array();
        foreach ($files as $key=>$file){
            $filename = basename($file);
            $templates[$key]['value'] =  substr($filename,0,strrpos($filename, '.'));
            $templates[$key]['filename'] = $filename;
            $templates[$key]['filepath'] = $file;
            $templates[$key]['filesize']=format_bytes(filesize($file));
            $templates[$key]['filemtime']=filemtime($file);
            $templates[$key]['ext'] = strtolower(substr($filename,strrpos($filename, '.')-strlen($filename)));
        }
        $this->view->assign('type', $type);
        $this->view->assign('empty', empty_list(4)); //空数据提示
        $this->view->assign('list' , $templates);    //加载数据
		return view('index');
	}
	
	// 新增友链页面
	public function add() {
		$type = 'html';
        $path=$this->template_path;
        $this->view->assign('type', $type);//当前显示的类型
        $this->view->assign('info',null);
		return view('add');
	}
	
	// 保存新增分类
	public function addsave() {
		
		$inputs = input('post.');
		$types = $inputs['type'] ? $inputs['type'] : 'html';
		$filename = $this->checkFilename($inputs['filename']);
        $type     = $this->checkFiletype($types);
        if($type=='html'){
            $path=$this->template_path;
        }else{
            $path=$this->template_path;
            // $path=$this->template_path.$type.'/';
        }
        $file = $path.$filename.'.'.$type;
        if(file_exists($file)){
            $this->error('文件已经存在!');
        }else{
            file_put_contents($file,stripslashes($inputs['content']));
            $this->success('添加成功!',url('index', ['type' => 'html']));
        }
		
	}
	
	// 编辑分类页面
	public function edit() {
		
		$filename = $this->checkFilename(input('file'));
        $type     = input('type') ? input('type') : 'html';
        if($type=='html'){
            $path=$this->template_path;
        }else{
            // $path=$this->template_path.$type.'/';
        }
        $file = $path.$filename;
        if(file_exists($file)){
            $file=iconv('gb2312','utf-8',$file);
            $content = file_get_contents($file);
            $info=[
                'filename'=>$filename,
                'file'=>$file,
                'content'=>$content,
                'type'=>$type
            ];
            $this->view->assign('info',$info);
        }else{
            $this->error('文件不存在！');
        }
        $this->view->assign('type', $type);//当前显示的类型
		return view('add');
	}
	
	// 保存编辑分类
	public function editsave() {
		
		$filename = $this->checkFilename(input('filename'));
        $type     = $this->checkFiletype(input('type', 'html'));
        if($type=='html'){
            $path=$this->template_path;
        }else{
            $path=$this->template_path;
        }
        $file = $path.$filename;
        if(file_exists($file)){
            file_put_contents($file,stripslashes(input('content')));
            if($type=='html'){
                $this->success('修改成功!',url('index', ['type' => 'html']));
            }else{
                $this->success('修改成功!',url('index', ['type' => $type]));
            }

        }else{
            $this->error('文件不存在!');
        }
	}
	
    //过滤文件名
    private function checkFilename($fileName)
    {
        $fileName = str_replace("/", "", $fileName);
        $fileName = str_replace("..", "", $fileName);
        $fileName = str_ireplace(".php", ".html", $fileName);
        $fileName = str_ireplace(".asp", ".html", $fileName);
        return $fileName;
    }

    // 过滤类型
    private function checkFiletype($fileType)
    {
        // $arr = ['html', 'css', 'js'];
        $arr = ['html'];
        if (!in_array($fileType, $arr)) {
            return 'html';
        } else {
            return $fileType;
        }
    }
	
	
	// 删除分类
	public function deletes() {
		
		$id = input('post.id');
		if(!$id){
			return ['error'=>1,'msg'=>'参数错误'];
		}
		
		//删除文件
        $filename = $id;
        $type = input('type') ? input('type') : 'html';
        if ($type == 'html') {
            $path = $this->template_path;
        } else {
            $path = $this->template_path;
        }
        $file = $path . $filename;
        if (file_exists($file)) {
            unlink($file);
            return ['error' => 0, 'msg' => '删除成功!'];
        } else {
            return ['error' => 1, 'msg' => '删除失败!'];
        }
	}
	
}
